// map/reduce/flat/flatmap
// isArray
// shuffle
// [1,2,3].sum()

Array.prototype.myIsArray = function(){
    return Object.prototype.toString.call(this) === '[object Array]'
}
console.log([].myIsArray())

Array.prototype.sum = function(){
    return this.reduce((prev, next) => prev + next, 0)
}
console.log([1,2,3].sum())

Array.prototype.myMap = function(fn){
    let res = [];
    for(let i = 0; i< this.length; i++){
      let item = fn.call(this, this[i], i, this)
      res.push(item)
    }
    return res;
}
console.log([1,2,3].myMap((item) => {return item}))

Array.prototype.myFlat = function(dep){
    let flatFn = (arr,d) => {
        let result = []
        for(let i = 0; i< arr.length; i++){
            if(!Array.isArray(arr[i]) || d === 0){
                result.push(arr[i])
            } else{
                result = result.concat(flatFn(arr[i], d-1))
            }
        }
        return result
    }
    let res = flatFn(this,dep)
    return res;
}
console.log([1,[2,[2,2]],[3,[3,[3,3]]]].myFlat(3))

Array.prototype.myReduce = function(fn, init){
    let startIndex = 0;
    if(init === undefined){
        init = this[0]
        startIndex = 1;
    }
    
    let res = init;
    for(let i = startIndex; i< this.length; i++){
        res = fn.call(this, res, this[i])
    }
    return res;
}
console.log([1,2,3].myReduce((p,n) => (p + n), 0))

Array.prototype.myFlatMap = function(fn){
    let res = [];
    for(let i = 0; i< this.length; i++){
        let item = fn.call(this, this[i])
        res = res.concat(item)
    }
    return res;
}
console.log([1,2,3].myFlatMap((a) => [a*1, a*2]))
console.log([1,2,3].flatMap((a) => [a*1, a*2]))


Array.prototype.myShulffe = function(){
    return this.sort((a, b) => Math.random() - 0.5)
}
console.log([1,2,3,4,5].myShulffe())